<template>
    <div class="person">
      <div>
        <p>1.监听ref基础类型</p>
        <button @click="singleRefValue++">修改数字</button>
      </div>
      <div>
        <p>2.监听ref对象类型</p>
        <button @click="changeRefObjectAgeVal">修改年龄</button>
        <button @click="changeRefObjectNameVal">修改名字</button>
        <button @click="changeRefObjectVal">修改整个人</button>
      </div>
      <div>
        <p>3.监听reactive对象类型</p>
        <button @click="changeReactiveObjectAgeVal">修改年龄</button>
        <button @click="changeReactiveObjectNameVal">修改名字</button>
        <button @click="changeReactiveObjectVal">修改整个人</button>
      </div>
    </div>
</template>


<script setup lang="ts">
  import { ref,reactive,watch,computed,watchEffect } from 'vue'
  import {type Person} from '@/type'
  defineOptions({
    name: '监听watch'
  })
  /**
   * watch监听
   * 1.监听ref基础类型
   * 2.监听ref对象类型
   * 3.监听reactive对象类型
   * 4.监听多个数据
   * 5.监听对象指定属性
   * */ 
  // 1.监听ref基础类型
  const singleRefValue = ref<number>(0)
  watch(singleRefValue,(newVal,oldVal)=>{
    console.log('监听ref基础类型',newVal,oldVal)
  })
  // 2.监听ref对象类型,如果监听ref对象，不加deep。修改里面的单个属性是监听不到的
  const objRefValue = ref<Person>({
    name:"leon",
    age:18
  })
  watch(objRefValue,(newV,oldV)=>{
    console.log("监听ref对象类型",newV,oldV)
  },{deep:true})
  watch(()=>objRefValue.value.age,(newV,oldV)=>{
    console.log("监听ref对象类型指定属性",newV,oldV)
  })
  function changeRefObjectAgeVal(){
    objRefValue.value.age++
  }
  function changeRefObjectNameVal(){
    objRefValue.value.name = "lisa"
  }
  function changeRefObjectVal(){
    objRefValue.value = {
      name:"mandi",
      age:27
    }
  }
  function changeReactiveObjectAgeVal(){
    objReactiveValue.age++
  }
  function changeReactiveObjectNameVal(){
    objReactiveValue.name = "lisa"
  }
  function changeReactiveObjectVal(){
    Object.assign(objReactiveValue,{
      name:"mandi",
      age:27
    })
  }
  // 3.监听reactive对象类型
  const objReactiveValue = reactive<Person>({
    name:"brook",
    age:99
  })
  watch(objReactiveValue,(newV,oldV)=>{
    console.log("监听reactive对象类型",newV,oldV)
  })

  // 监听多个对象
  watch([singleRefValue,objRefValue,objReactiveValue],([newSingleRefVal,newObjRefVal,newObjReactiveVal],[oldSingleRefVal,oldObjRefVal,oldObjReactiveVal])=>{
    console.log("监听多个对象",newSingleRefVal,oldSingleRefVal,newObjRefVal,oldObjRefVal,newObjReactiveVal,oldObjReactiveVal)
  })
  
  
  watchEffect(()=>{
    console.log("watchEffect监听",singleRefValue.value,objRefValue.value,objReactiveValue)
  })
  
</script>

<style scoped>
    .person{
        background-color: skyblue;
        padding: 10px;
        border-radius: 10px;
        box-shadow: 0 0 10px gray;
    }
    button{
        margin:0 5px;
    }
</style>